class UiSlider extends HTMLElement {
    constructor() {
        super();
        this.attachShadow({ mode: 'open' });

        // 默认值
        this._value = 0;
        this._min = 0;
        this._max = 100;
        this._step = 1;

        this.render();
        this._thumb = this.shadowRoot.querySelector('.slider-thumb');
        this._container = this.shadowRoot.querySelector('.slider-container');
        this._valueDisplay = this.shadowRoot.querySelector('.slider-value');
        this._fill = this.shadowRoot.querySelector('.slider-fill');
        this._containerRect = null;

        this.setupEventListeners();
    }

    // 定义组件的观察属性
    static get observedAttributes() {
        return ['value', 'min', 'max', 'step'];
    }

    // 属性变化时的回调
    attributeChangedCallback(name, oldValue, newValue) {
        if (oldValue !== newValue) {
            switch (name) {
                case 'value':
                    this._value = parseFloat(newValue) || 0;
                    this.updateSlider();
                    break;
                case 'min':
                    this._min = parseFloat(newValue) || 0;
                    this.updateSlider();
                    break;
                case 'max':
                    this._max = parseFloat(newValue) || 100;
                    this.updateSlider();
                    break;
                case 'step':
                    this._step = parseFloat(newValue) || 1;
                    this.updateSlider();
                    break;
            }
        }
    }

    // 获取属性值
    get value() {
        return this._value;
    }

    set value(val) {
        this._value = parseFloat(val) || 0;
        this.setAttribute('value', this._value);
        this.updateSlider();
    }

    get min() {
        return this._min;
    }

    set min(val) {
        this._min = parseFloat(val) || 0;
        this.setAttribute('min', this._min);
        this.updateSlider();
    }

    get max() {
        return this._max;
    }

    set max(val) {
        this._max = parseFloat(val) || 100;
        this.setAttribute('max', this._max);
        this.updateSlider();
    }

    get step() {
        return this._step;
    }

    set step(val) {
        this._step = parseFloat(val) || 1;
        this.setAttribute('step', this._step);
        this.updateSlider();
    }

    render() {
        this.shadowRoot.innerHTML = `
            <style>
                :host {
                    display: flex;
                    align-items: center;
                    width: 200px;
                    font-family: Arial, sans-serif;
                }
                
                .slider-container {
                    position: relative;
                    flex: 1;
                    height: 20px;
                    margin-right: 10px;
                }
                
                .slider-track {
                    position: absolute;
                    top: 50%;
                    left: 0;
                    right: 0;
                    height: 4px;
                    background: #ddd;
                    border-radius: 2px;
                    transform: translateY(-50%);
                }
                
                .slider-fill {
                    position: absolute;
                    top: 50%;
                    left: 0;
                    height: 4px;
                    background: #6648EA;
                    border-radius: 2px;
                    transform: translateY(-50%);
                    transition: width 0.1s ease;
                }
                
                .slider-thumb {
                    position: absolute;
                    top: 50%;
                    width: 18px;
                    height: 18px;
                    background: #fff;
                    border: 2px solid #6648EA;
                    border-radius: 50%;
                    cursor: pointer;
                    transform: translate(-50%, -50%);
                    box-shadow: 0 2px 4px rgba(0,0,0,0.2);
                    transition: transform 0.1s ease;
                    touch-action: none;
                    -webkit-touch-callout: none;
                    -webkit-user-select: none;
                    user-select: none;
                }
                
                .slider-thumb:hover {
                    transform: translate(-50%, -50%) scale(1.1);
                }
                
                .slider-thumb:active {
                    transform: translate(-50%, -50%) scale(1.2);
                }

                /* 触摸设备优化 */
                @media (hover: none) and (pointer: coarse) {
                    .slider-thumb {
                        width: 24px;
                        height: 24px;
                    }
                    
                    .slider-thumb:active {
                        transform: translate(-50%, -50%) scale(1.1);
                    }
                }
                
                .slider-value {
                    min-width: 40px;
                    text-align: right;
                    color: #333;
                    font-size: 14px;
                }
            </style>
            
            <div class="slider-container">
                <div class="slider-track"></div>
                <div class="slider-fill"></div>
                <div class="slider-thumb"></div>
            </div>
            <div class="slider-value">${this._value}</div>
        `;
    }

    setupEventListeners() {
        const thumb = this._thumb;
        const container = this._container;
        let isDragging = false;
        let isTouching = false;
        const getContainerRect = () => {
            return this._containerRect || (this._containerRect = this._container.getBoundingClientRect());
        }

        // 鼠标按下开始拖拽
        thumb.addEventListener('mousedown', (e) => {
            getContainerRect();
            isDragging = true;
            e.preventDefault();
        });

        // 鼠标移动更新值
        document.addEventListener('mousemove', (e) => {
            if (!isDragging) return;

            const rect = this._containerRect;

            const x = e.clientX - rect.left;
            const percentage = Math.max(0, Math.min(1, x / rect.width));
            const newValue = this._min + percentage * (this._max - this._min);

            // 实时更新滑块位置和填充条，不等待步长对齐
            this.updateSliderPosition(percentage, newValue);
        });

        // 鼠标释放停止拖拽
        document.addEventListener('mouseup', (e) => {
            if (isDragging) {
                isDragging = false;
                // 拖拽结束时进行步长对齐
                const rect = this._containerRect;
                const x = e.clientX - rect.left;
                const percentage = Math.max(0, Math.min(1, x / rect.width));
                const newValue = this._min + percentage * (this._max - this._min);
                this.updateValue(newValue);
            }
        });

        // 触摸开始
        thumb.addEventListener('touchstart', (e) => {
            getContainerRect();
            isTouching = true;
            e.preventDefault();
        });

        // 触摸移动更新值
        document.addEventListener('touchmove', (e) => {
            if (!isTouching) return;

            const rect = this._containerRect;
            const touch = e.touches[0];
            const x = touch.clientX - rect.left;
            const percentage = Math.max(0, Math.min(1, x / rect.width));
            const newValue = this._min + percentage * (this._max - this._min);

            // 实时更新滑块位置和填充条，不等待步长对齐
            this.updateSliderPosition(percentage, newValue);

            // 防止页面滚动
            e.preventDefault();
        });

        // 触摸结束
        document.addEventListener('touchend', (e) => {
            if (isTouching) {
                isTouching = false;
                // 触摸结束时进行步长对齐
                const rect = this._containerRect;
                const touch = e.changedTouches[0];
                const x = touch.clientX - rect.left;
                const percentage = Math.max(0, Math.min(1, x / rect.width));
                const newValue = this._min + percentage * (this._max - this._min);
                this.updateValue(newValue);
            }
        });

        // 点击轨道直接跳转
        container.addEventListener('click', (e) => {
            getContainerRect();
            if (e.target === thumb) return;

            const rect = this._containerRect;
            const x = e.clientX - rect.left;
            const percentage = Math.max(0, Math.min(1, x / rect.width));
            const newValue = this._min + percentage * (this._max - this._min);

            this.updateValue(newValue);
        });

        // 触摸点击轨道直接跳转
        container.addEventListener('touchend', (e) => {
            if (isTouching) return; // 如果正在拖拽，不处理点击

            getContainerRect();
            if (e.target === thumb) return;

            const rect = this._containerRect;
            const touch = e.changedTouches[0];
            const x = touch.clientX - rect.left;
            const percentage = Math.max(0, Math.min(1, x / rect.width));
            const newValue = this._min + percentage * (this._max - this._min);

            this.updateValue(newValue);
        });

        // 键盘支持
        thumb.addEventListener('keydown', (e) => {
            getContainerRect();
            let newValue = this._value;

            switch (e.key) {
                case 'ArrowLeft':
                case 'ArrowDown':
                    newValue = Math.max(this._min, this._value - this._step);
                    break;
                case 'ArrowRight':
                case 'ArrowUp':
                    newValue = Math.min(this._max, this._value + this._step);
                    break;
                case 'Home':
                    newValue = this._min;
                    break;
                case 'End':
                    newValue = this._max;
                    break;
                default:
                    return;
            }

            e.preventDefault();
            this.updateValue(newValue);
        });

        // 使滑块可聚焦
        thumb.setAttribute('tabindex', '0');
    }

    updateValue(newValue) {
        const oldValue = this._value;

        // 限制在最小值和最大值之间
        newValue = Math.max(this._min, Math.min(this._max, newValue));

        // 根据步长调整值
        if (this._step > 0) {
            const steps = Math.round((newValue - this._min) / this._step);
            this._value = this._min + steps * this._step;
        } else {
            this._value = newValue;
        }

        if (oldValue !== this._value) {
            this.setAttribute('value', this._value);
            this.updateSlider();

            // 触发自定义事件
            this.dispatchEvent(new CustomEvent('change', {
                detail: {
                    value: this._value,
                    oldValue: oldValue
                },
                bubbles: true
            }));
        }
    }

    updateSlider() {
        const percentage = ((this._value - this._min) / (this._max - this._min)) * 100;
        this.updateSliderPosition(percentage / 100, this._value);

        // 更新显示元素
        const valueDisplay = this._valueDisplay;
        if (valueDisplay) valueDisplay.textContent = this._value.toFixed(1);
    }

    updateSliderPosition(percentage, value) {
        const fill = this._fill;
        const thumb = this._thumb;
        const valueDisplay = this._valueDisplay;

        if (fill) fill.style.width = `${percentage * 100}%`;
        if (thumb) thumb.style.left = `${percentage * 100}%`;
        if (valueDisplay) valueDisplay.textContent = value.toFixed(1);
    }
}

// 注册自定义元素
customElements.define('ui-slider', UiSlider);
